package com.gzw.dms.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.adapter.QsAdapter;
import com.gzw.dms.base.BaseFragment;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.L;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/25.
 */
public class PsOrderFrmager extends BaseFragment {
    private ListView lv_dingdan;
    private List<ShippingOrderInfo> shippingOrderInfo;
    private Context mContext;
    private String state="1";
    private SwipeRefreshLayout mSwipeLayout;
    private String rownum = "100";
    private String rows = "0";
    private String order_num = "";
    private String shiping_order_goid = "";
    private String custom_name = "";
    private String shiping_order_num = "";
    private String send_time = "";
    private String send_mechanism = "";
    private String end_address = "";
    private String receipt_tel = "";
    private String receipt_name = "";
    private String end_time = "";

    private int refresh = 0;
    private View progress;
    private ProgressDialog mProgressDialog;
    private String tag = "PsOrderFrmager---->";
    private QsAdapter qsAdapter;
    private TextView tv_select;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_order, null);
    }

    @Override
    protected void initViews() {
        lv_dingdan = (ListView) findViewById(R.id.lv_dingdan);
        tv_select = (TextView) findViewById(R.id.tv_select);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        progress=findViewById(R.id.include_pb);
    }

    @Override
    protected void initEvents() {
        lv_dingdan.setOnItemClickListener(new mOnItemClick());
        tv_select.setOnClickListener(new myOnClick());

        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh = 1;
                ShowOrderTask showOrderTask = new ShowOrderTask();
                showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                        custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time);
            }
        });
    }

    @Override
    protected void initData() {
        L.i(tag, "initData()");
        mContext = getActivity();
        setHasOptionsMenu(true);

        shippingOrderInfo = new ArrayList<>();
        refresh = 0;
        ShowOrderTask showOrderTask = new ShowOrderTask();
        showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time);
    }


    /**
     * Created by Wangzhiqiang on 2015-10-11
     * 单击事件
     */
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_select:
                    Intent mIntetn = new Intent();
                    mIntetn.putExtra("back","0");
                    mIntetn.setClass(mContext, TJSelectActivity.class);
                    startActivityForResult(mIntetn, 1);
                    break;
            }
        }
    }

    class mOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ShippingOrderInfo shippingOrder = (ShippingOrderInfo) parent.getItemAtPosition(position);
            Intent mIntetn = new Intent();
            Bundle bundle = new Bundle();
            mIntetn.setClass(mContext, ShippingOrderDetailActivity.class);
            bundle.putSerializable("shippingOrder", shippingOrder);
            mIntetn.putExtra("driver_id", "");
            bundle.putString("state", state);
            mIntetn.putExtra("fpstste","0");
            mIntetn.putExtras(bundle);
            startActivityForResult(mIntetn, 1);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            refresh = 0;
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                    custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time);

        }else if(resultCode == 2){
            refresh = 0;
            String order_num1 = (String) data.getExtras().get("order_num");
            String shiping_order_goid1 = (String) data.getExtras().get("shiping_order_goid");
            String custom_name1
                    = (String) data.getExtras().get("custom_name");
            String receipt_name1
                    = (String) data.getExtras().get("receipt_name");
            String end_address1
                    = (String) data.getExtras().get("end_mechanism");
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,order_num1,shiping_order_goid1,
                    custom_name1,receipt_name1,send_time,send_mechanism,end_address1,receipt_tel,end_time);
        }
    }

    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            if (refresh == 0) {
//                progress.setVisibility(View.VISIBLE);
                mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
                mProgressDialog.setCancelable(true);
                mProgressDialog.setCanceledOnTouchOutside(false);

            } else if (refresh == 1) {

            }else if(refresh == 2){
                mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
                mProgressDialog.setCancelable(true);
                mProgressDialog.setCanceledOnTouchOutside(false);

            }
        }

        protected String doInBackground(String... params) {

            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("page", params[0]);
            map.put("row", params[1]);
            map.put("shiping_order_num",params[2]);
            map.put("shiping_order_goid",params[3]);
            map.put("custom_name",params[7]);
            map.put("receipt_name",params[5]);
            map.put("send_time",params[6]);
            map.put("send_mechanism",params[4]);
            map.put("end_mechanism",params[8]);
            map.put("end_address","");
            map.put("receipt_tel",params[9]);
            map.put("end_time",params[10]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetSignOrderInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (refresh == 0) {
//                progress.setVisibility(View.GONE);
                mProgressDialog.dismiss();
            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(false);
            }else if(refresh == 2){
                mProgressDialog.dismiss();
            }
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0){
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    shippingOrderInfo = JsonUtil.getPersons(successMsg, new TypeToken<List<ShippingOrderInfo>>() {
                    }.getType());
                    qsAdapter = new QsAdapter(mContext, shippingOrderInfo);
                    lv_dingdan.setAdapter(qsAdapter);
                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu_home; this adds items to the action bar if it is present.
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_refresh, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_refresh:
                ShippingOrderInfo shippingOrder = new ShippingOrderInfo();
                for (int i = 0; i < shippingOrderInfo.size(); i++) {
                    if (qsAdapter.getIsSelected().get(i)) {
                        shippingOrder = shippingOrderInfo.get(i);
                    }
                }
                if(shippingOrder.getShiping_order_id()==null){
                    T.showShort(mContext,"请先选择要签收的运单!");
                }else {
                    String is_abnormal = shippingOrder.getIs_abnormal();
                    if (is_abnormal.equals("1") || is_abnormal.equals("2")) {
                        T.showShort(mContext, "该运单已异常上报，请联系项目部先处理");

                    }else {
                        Integer waybill= shippingOrder.getWaybill_state();
                        if (waybill==1 || waybill==2){
                            T.showShort(mContext,"该运单已进行调整，请等待处理...");
                        }else {
                            Intent mIntetn = new Intent();
                            Bundle bundle = new Bundle();
                            mIntetn.setClass(mContext, ScanActivity.class);
                            bundle.putSerializable("shippingOrder", shippingOrder);
                            bundle.putString("state", state);
                            mIntetn.putExtra("fpstste", "0");
                            mIntetn.putExtras(bundle);
                            startActivityForResult(mIntetn, 1);
                        }
                    }


                }
                    break;
                }
                return super.onOptionsItemSelected(item);
        }


}